/**
 * JS与原生iOS双向通信封装
 */

// 通信方法映射表
const NativeBridge = {
  // 调用原生方法
  callNative(methodName, params = {}, callback) {
    try {
      if (
        window.webkit &&
        window.webkit.messageHandlers &&
        window.webkit.messageHandlers[methodName]
      ) {
        const message = {
          params: params,
          callbackId: callback ? this._generateCallbackId() : null
        }

        window.webkit.messageHandlers[methodName].postMessage(message)

        if (callback) {
          this._callbacks[message.callbackId] = callback
        }
      } else {
        console.warn(`Native method ${methodName} not found`)
      }
    } catch (e) {
      console.error(`Call native method ${methodName} failed:`, e)
    }
  },

  // 原生调用JS方法
  registerHandler(handlerName, handler) {
    window[handlerName] = function (data) {
      try {
        handler(data)
      } catch (e) {
        console.error(`Execute handler ${handlerName} failed:`, e)
      }
    }
  },

  // 回调函数存储
  _callbacks: {},

  // 生成唯一回调ID
  _generateCallbackId() {
    return 'cb_' + Date.now() + '_' + Math.floor(Math.random() * 10000)
  },

  // 处理原生回调
  _handleNativeCallback(callbackId, response) {
    if (this._callbacks[callbackId]) {
      this._callbacks[callbackId](response)
      delete this._callbacks[callbackId]
    }
  }
}

// 常用方法封装
export const Hybrid = {
  // 获取用户信息
  getUserInfo() {
    return new Promise((resolve, reject) => {
      NativeBridge.callNative('getUserInfo', {}, (res) => {
        if (res.success) {
          resolve(res.data.token)
        } else {
          reject(res.error)
        }
      })
    })
  },

  // 关闭WebView
  closeWebView() {
    NativeBridge.callNative('closeWebView')
  },

  // 返回指定页面
  navigateBackTo({ value = 'login', ...restParams }) {
    NativeBridge.callNative('navigateBackTo', { value, ...restParams })
  },
  // 设置原生导航头
  setNavigationBarVisible({ value = '1' }) {
    // 0 为显示，1 为隐藏
    NativeBridge.callNative('setNavigationBarVisible', value)
  },
  // 获取定位
  getLocation() {
    return new Promise((resolve, reject) => {
      NativeBridge.callNative('getLocation', {}, (res) => {
        if (res.success) {
          resolve(res.data)
        } else {
          reject(res.error)
        }
      })
    })
  },

  // 打电话
  phoneFunc({ value = '' }) {
    NativeBridge.callNative('phoneFunc', value)
  }
}

// 注册原生调用JS的全局方法
NativeBridge.registerHandler('nativeCallJS', function (message) {
  console.log('原生的回掉信息message', message)
  // 统一将字符串转为对象
  const parsedMessage = typeof message === 'string' ? JSON.parse(message) : message
  console.log('转换后的回掉信息message', parsedMessage)
  if (parsedMessage.callbackId) {
    NativeBridge._handleNativeCallback(parsedMessage.callbackId, parsedMessage.data)
  }
})

export default Hybrid
